package com.mixed;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.util.*;

import java.util.*;

public class Mail {

    //filepath为文件所在路径,filename指定文件发送名。此用于多附件发送
    public static void sendMail(String receiver, String[] filepath, String subject, String[] filename) {

        Properties props = new Properties();
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "smtp.qq.com");
        props.put("mail.user","3154572951@qq.com");
        props.put("mail.password","bvotdlmkslxndeeh");//smtp认证
 
        //smtp验证
        Authenticator authenticator = new Authenticator() {
 
            protected PasswordAuthentication getPasswordAuthentication() {
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };

        //获得一邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        MimeMessage message = new MimeMessage(mailSession);
        try{
            InternetAddress from = new InternetAddress(props.getProperty("mail.user"));
            message.setFrom(from);
            InternetAddress to = new InternetAddress(receiver);
            message.setRecipient(Message.RecipientType.TO, to);
            message.setSubject(subject, "UTF-8");
            MimeMultipart multipart = new MimeMultipart();
            for(int i = 0; i < filepath.length; i++) {
                String path = filepath[i];
                String name = filename[i];
                MimeBodyPart file = new MimeBodyPart();
                DataHandler dataHandler1 = new DataHandler(new FileDataSource(path));
                file.setDataHandler(dataHandler1);
                file.setFileName(MimeUtility.encodeText(name));
                multipart.addBodyPart(file);
            }
            message.setContent(multipart);
            message.saveChanges();
            Transport transport = mailSession.getTransport("smtp");
            transport.connect("smtp.qq.com","3154572951@qq.com","bvotdlmkslxndeeh");
            transport.sendMessage(message,message.getAllRecipients());
            transport.close();
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
    }

    public static void sendMail(String receiver, String filepath, String subject, String filename) throws Exception{
        sendMail(receiver, new String[]{filepath}, subject, new String[]{filename});
    }

}
